<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>

      <!-- 添加分类按钮 -->
      <el-row class="row">
        <el-col>
          <el-button type="primary" @click="openAddCate">添加分类</el-button>
        </el-col>
      </el-row>
                  <el-alert
        title="注意：只允许添加第三级分类！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 表格区 -->
      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCateById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addCateFormRules"
        ref="addForm"
        label-width="80px"
      >
        <!-- 添加用户内容主体区域 -->
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            expandTrigger="hover"
            v-model="selectedKey"
            :options="parentCateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 添加用户底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="cateinfo"
        :rules="editCateFormRules"
        ref="editRoleFormRef"
        label-width="80px"
        @close="editDialogClosed"
      >
        <!-- 修改分类内容主体区域 -->
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="cateinfo.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 修改分类底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCateInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类的数据列表
      cateList: [],
      //总的数据条数
      total: 0,
      //添加分类对象数据
      addForm: {
        //分类名称
        cat_name: '',
        // 父级分类ID
        cat_pid: 0,
        //分类层级
        cat_level: 0,
      },
      //监听添加分类对话框的显示隐藏
      addCateDialogVisible: false,
      //监听编辑分类对话框的显示隐藏
      editDialogVisible: false,
      //编辑分类的分类数据
      cateinfo: {
        cat_name: '',
        id: '',
      },
      //父级分类列表的数据
      parentCateList: [],
      cascaderProps: {
        value: 'cat_pid',
        label: 'cat_name',
        children: 'children',
      },
      //选中的父级分类的ID数据
      selectedKey: [],
      //为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          //将当前列定义为模板列
          type: 'template',
          //当前模板列的名称
          template: 'isok',
        },
        {
          label: '排序',
          //将当前列定义为模板列
          type: 'template',
          //当前模板列的名称
          template: 'order',
        },
        {
          label: '操作',
          //将当前列定义为模板列
          type: 'template',
          //当前模板列的名称
          template: 'opt',
        },
      ],
      //添加分类规范
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          {
            min: 3,
            max: 16,
            message: '长度在 3 到 16 个字符',
            trigger: 'blur',
          },
        ],  
        cat_Pid: [
          { required: true, message: '请选择父级分类', trigger: 'blur' },
        ],
      },
      //编辑分类规范
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          {
            min: 3,
            max: 16,
            message: '长度在 3 到 16 个字符',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.cateList = res.data.result
      this.total = res.data.total
    },
    //监听当前页码的变化
    handleCurrentChange(newSize) {
      this.queryInfo.pagenum = newSize
      this.getCateList()
    },
    //监听显示数据条数的变化
    handleSizeChange(newPage) {
      this.queryInfo.pagesize = newPage
      this.getCateList()
    },
    //监听添加分类对话框的关闭事件
    addDialogClosed() {
      this.$refs.addForm.resetFields()
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
      this.selectedKey = []
    },
    //获取父级分类的数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.parentCateList = res.data
    },
    //点击确认按钮添加新分类
    addCate() {
      this.$refs.addForm.validate(async (vaild) => {
        if (!vaild) return
        //发起修改信息的数据请求
        const { data: res } = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加分类失败')
        }
        this.getCateList()
        this.addCateDialogVisible = false
        this.$message.success('添加分类成功')
      })
    },
    // 打开添加角色对话框
    openAddCate() {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    handleChange() {
      //判断：如果selectedKey的length大于0，则证明选中了分类
      if (this.selectedKey.length > 0) {
        //将选中的父级分类的ID赋值给addform
        this.addForm.cat_pid = this.selectedKey[this.selectedKey.length - 1]
        this.addForm.cat_level = this.selectedKey.length
        return
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    //打开编辑分类页面
    editCate(cate) {
      this.editDialogVisible = true
      console.log(cate)
      this.cateinfo.cat_name = cate.cat_name
      this.cateinfo.id = cate.cat_id
    },
    //监听编辑分类对话框关闭后清空事件
    editDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    //点击确定，修改分类
    saveCateInfo() {
      this.$refs.editRoleFormRef.validate(async (vaild) => {
        if (!vaild) return
        //发送添加用户网络请求
        const { data: res } = await this.$http.put(
          'categories/' + this.cateinfo.id,
          { cat_name: this.cateinfo.cat_name }
        )
        if (res.meta.status !== 200) {
          this.$message.error('编辑分类失败')
        }
        this.$message.success('编辑分类成功')
        // 隐藏编辑分类对话框
        this.editDialogVisible = false
        // 重新获取分类数据
        this.getCateList()
      })
    },
    // 删除分类事件
   async removeCateById(id) {
      const confirmResult= await  this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch( err => err )
        if(confirmResult !=='confirm') return;
      const{data:res}= await this.$http.delete('categories/'+id);
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getCateList()
    },
  },
}
</script>
<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
.row{
  margin-bottom: 10px;
}
</style>